﻿using DatabaseCore;
using DatabaseCore.Sqlite;
using Service.src.NW.Model;

namespace NW_WEB_Service.com.app.services
{
    public class DBService
    {
        public static DataSourceClient DBInstance { get; private set; }

        public DBService(int defaultDbIndex = 0)
        {
            if (DBInstance == null)
            {
                // 从缓存获取实例，并验证是否为有效连接
                var instance = AppData.DatabaseCache[defaultDbIndex] as SqliteHelper;
                if (instance == null)
                {
                    // 缓存为空时主动创建并初始化
                    instance = SqliteHelper.Create();
                    AppData.DatabaseCache[defaultDbIndex] = instance;
                }
                else
                {
                    // 验证现有实例是否已连接
                    if (!instance.IsConnected)
                    {
                        instance.ConnectionSqlite(); // 重新连接
                    }
                }
                DBInstance = instance;
            }
        }
    }
}
